import { Component, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { STChange, STColumn, STComponent, STData } from '@delon/abc/st';
import { SFDateWidgetSchema } from '@delon/form';
import { SearchDrawerService } from '@shared';
import { NzModalService } from 'ng-zorro-antd/modal';
import { BasicTableComponent } from 'src/app/routes/commom';
import { TaxManagementService } from '../../services/tax-management.service';

@Component({
  selector: 'app-tax-management-individual-declare',
  templateUrl: './individual-declare.component.html',
  styleUrls: ['../../../commom/less/commom-table.less']
})
export class TaxManagementIndividualDeclareComponent extends BasicTableComponent implements OnInit {
  columns!: STColumn[];
  tabType!: string;
  tabs: any[] = [
    { name: '待申报', value: '0' },
    { name: '待审核', value: '1' },
    { name: '已通过', value: '2' },
    { name: '不通过', value: '3' },
    { name: '全部', value: '' }
  ];
  selectedIndex = '0'; //选择的项目
  serviceTel = '';
  isVisible: boolean = false;
  checkedList: any[] = [];

  // selectedRows:any[] =[];
  constructor(
    public service: TaxManagementService,
    private router: Router,
    private ar: ActivatedRoute,
    private modal: NzModalService,
    public searchDrawerService: SearchDrawerService
  ) {
    super(searchDrawerService);
  }

  /**
   * 查询参数
   */
  get reqParams() {
    const params = Object.assign({}, this.sf?.value || {});
    if (this.selectedIndex !== '4') {
      params.declareStatus = this.selectedIndex;
    }
    delete params._$expand;
    console.log(params);
    return { ...params };
  }

  /**
   * 选中行
   */
  get selectedRows() {
    return this.st?.list.filter((item: any) => item.checked) || [];
  }

  /**
   * 程序初始化入口
   */
  ngOnInit() {
    this.initSF();
    this.initST();
  }

  /**
   * 初始化查询表单
   */
  initSF() {
    this.schema = {
      properties: {
        _$expand: { type: 'boolean', ui: { hidden: true } },
        driverName: { title: '司机姓名', type: 'string', ui: { placeholder: '请输入' } },
        telephone: {
          type: 'string',
          title: '联系电话',
          ui: {
            placeholder: '请输入'
          }
        },
        cardNumber: {
          title: '证件号码',
          type: 'string',
          ui: {
            placeholder: '请输入证件号码'
          }
        },
        declareStatus: {
          title: '申报状态',
          type: 'string',
          ui: {
            placeholder: '请选择',
            widget: 'dict-select',
            params: { dictKey: 'taxincome:declare:status' },
            containsAllLabel: true
          }
        },

        overtime: {
          title: '是否逾期',
          type: 'string',
          enum: [
            { value: '', label: '全部' },
            { value: '0', label: '否' },
            { value: '1', label: '是' }
          ],
          ui: {
            placeholder: '请选择',
            widget: 'select',
            containsAllLabel: true
          },
          default: ''
        },
        taxDate: {
          title: '税款所属期',
          type: 'string',
          ui: {
            widget: 'sl-from-to',
            type: 'date',
            format: 'yyyy-MM-dd'
          } as SFDateWidgetSchema
        },
        declareDate: {
          title: '申报日期',
          type: 'string',
          ui: {
            widget: 'sl-from-to',
            type: 'date',
            format: 'yyyy-MM-dd'
          } as SFDateWidgetSchema
        },
        ltdId: {
          type: 'string',
          title: '网络货运人',
          ui: {
            widget: 'select',
            placeholder: '请选择',
            allowClear: true,
            asyncData: () => this.service.getNetworkFreightForwarder()
          }
        }
      }
    };
  }

  /**
   * 初始化数据列表
   */
  initST() {
    this.columns = [
      { title: '', type: 'checkbox', className: 'text-center', width: '60px' },
      {
        title: '序号',
        className: 'text-center',
        width: '60px',
        format: (item: STData, col: STColumn, idx: number) => {
          return (this.st.pi * this.st.ps) - this.st.ps + idx + 1 + ''
        }
      },
      {
        title: '申报状态',
        index: 'declareStatus',
        className: 'text-center',
        width: '120px',
        type: 'badge',
        badge: {
          '0': { text: '待申报', color: 'default' },
          '1': { text: '待审核', color: 'processing' },
          '2': { text: '已通过', color: 'success' },
          '3': { text: '不通过', color: 'error' }
        }
      },
      {
        title: '是否逾期',
        index: 'overtime',
        className: 'text-center',
        width: '120px',
        type: 'enum',
        enum: { '0': '否', '1': '是' }
      },
      {
        title: '税款所属期起',
        index: 'skssqq',
        className: 'text-center',
        width: '150px'
      },
      { title: '税款所属期止', index: 'skssqz', className: 'text-center', width: '150px' },
      {
        title: '纳税人名称',
        index: 'nsrmc',
        className: 'text-center',
        width: '180px'
      },
      { title: '纳税人识别号', index: 'nsrsbh', className: 'text-center', width: '200px' },
      { title: '姓名', index: 'xm', className: 'text-center', width: '200px' },
      { title: '证件类型', index: 'sfzjlx', className: 'text-center', width: '200px' },
      { title: '证件号码', index: 'sfzjhm', className: 'text-center', width: '200px' },
      { title: '联系电话', index: 'lxdh', className: 'text-center', width: '200px' },
      { title: '国家（地区）', index: 'gjdq', className: 'text-center', width: '200px' },
      { title: '所属行业', index: 'hy', className: 'text-center', width: '200px' },
      { title: '征收项目', index: 'zsxm', className: 'text-center', width: '200px' },
      { title: '征收品目', index: 'zsmp', className: 'text-center', width: '200px' },
      {
        title: '计税依据',
        index: 'jsyj',
        className: 'text-center',
        width: '200px',
        type: 'widget',
        widget: { type: 'currency-chy', params: ({ record }) => ({ value: record.jsyj }) }
      },
      {
        title: '税率',
        index: 'sl',
        render: 'sl',
        className: 'text-center',
        width: '200px',
        format: item => `${item.sl ? ((item.sl as number) * 100).toFixed(2) : 0}%`
      },
      {
        title: '应纳税额',
        index: 'ynse',
        className: 'text-center',
        width: '180px',
        type: 'widget',
        widget: { type: 'currency-chy', params: ({ record }) => ({ value: record.ynse }) }
      },
      {
        title: '减免税额',
        index: 'jmse',
        className: 'text-center',
        width: '180px',
        type: 'widget',
        widget: { type: 'currency-chy', params: ({ record }) => ({ value: record.jmse }) }
      },
      {
        title: '已缴纳税额',
        index: 'yjnse',
        className: 'text-center',
        width: '180px',
        type: 'widget',
        widget: { type: 'currency-chy', params: ({ record }) => ({ value: record.yjnse }) }
      },
      {
        title: '应代征税额',
        index: 'dzse',
        className: 'text-center',
        width: '180px',
        type: 'widget',
        widget: { type: 'currency-chy', params: ({ record }) => ({ value: record.dzse }) }
      },
      {
        title: '已代征税额',
        index: 'ydzse',
        className: 'text-center',
        width: '150px',
        type: 'widget',
        widget: { type: 'currency-chy', params: ({ record }) => ({ value: record.ydzse }) }
      },
      {
        title: '申报日期',
        index: 'sbrq',
        className: 'text-center',
        width: '180px',
      }
    ];
  }

  /**
   *更正
   * @param record 记录实例
   */
  recall() {
    if (this.selectedRows.length === 0) {
      this.openWainingModal('请选择需要更正的数据');
      return;
    }
    // this.modal.confirm({
    //   nzTitle: '撤回提示',
    //   nzContent: ' 撤回后可以重新上传，重新上传会覆盖已上传数据，确定要撤回？',
    //   nzOkText: '确定',
    //   nzCancelText: '取消',
    //   nzOnOk: () => {
    //     this.service.request(this.service.$api_recall_reporting, { rows: this.selectedRows }).subscribe((res: any) => {
    //       if (res) {
    //         this.service.msgSrv.success('撤销成功');
    //         this.search();
    //       }
    //     });
    //   }
    // });
  }
  /**
   *修改
   * @param record 记录实例
   */
  uploadSetting() {
    if (this.selectedRows.length === 0) {
      this.openWainingModal('请选择需要修改的数据！');
      return;
    }
    // this.isVisible = true
  }
  /**
   *撤销
   * @param record 记录实例
   */
  unnormal(value: any) {
    this.modal.confirm({
      nzTitle: '税务审核结果',
      nzContent: `${value?.exceptionInfo}`,
      nzOkText: '确定',
      nzCancelText: '',
      nzOnOk: () => {
        this.service.request(this.service.$api_recall_reporting, { rows: this.selectedRows }).subscribe((res: any) => {
          if (res) {
            this.service.msgSrv.success('撤销成功');
            this.search();
          }
        });
      }
    });
  }

  selectChange(item: any) {
    this.selectedIndex = item?.value || '';
    setTimeout(() => {
      this.st.load(1);
    });
  }

  /**
   * 查看当行数据
   */
  view(record: STData) {
    // this.router.navigate(['../view', record.uuid], { relativeTo: this.ar });
    this.router.navigate(['../detail'], {
      queryParams: {
        id: record.id
      },
      relativeTo: this.ar
    });
  }

  // appeal(item: any) {
  //   const modalRef = this.modal.create({
  //     nzTitle: '申诉',
  //     nzWidth: '40%',
  //     nzContent: CtcAppealComponent,
  //     nzComponentParams: {
  //       i: item,
  //       status: 'add'
  //     },
  //     nzFooter: null
  //   });
  //   modalRef.afterClose.subscribe(res => {
  //     if (res) {
  //       this.search({ representationsStatus: '' });
  //     }
  //   })
  // }

  /**
   * 申报
   */
  upload() {
    if (this.selectedRows.length === 0) {
      this.openWainingModal('请选择需要申报的数据');
      return;
    }
    const ids = this.selectedRows.map(item => item?.id);
    this.service.request(this.service.$api_declare_tax, ids).subscribe((res: any) => {
      if (res) {
        this.service.msgSrv.success('申报成功');
        this.search();
      }
    });
  }

  /**
   *
   * @param params 更新数据
   */
  resetData() {
    let params: any;
    if (this.selectedRows.length === 0) {
      params = [];
    } else {
      params = [];
      this.selectedRows.forEach(item => {
        params.push(item.id);
      });
    }
    this.service.request(this.service.$api_get_taxDeclaration_updateAll, params).subscribe((res: any) => {
      if (res) {
        this.service.msgSrv.success('更新成功');
        this.st.load(1);
      }
    });
  }

  /**
   * 查看校验结果
   */
  viewResult(item: any) {
    // const modalRef = this.modal.create({
    //   nzTitle: '本地校验结果',
    //   nzWidth: 1200,
    //   nzContent: TaxManagementOrderVerifyResultComponent,
    //   nzComponentParams: {
    //     record: item
    //   },
    //   nzFooter: null
    // });
    // modalRef.afterClose.subscribe(res => {
    // })
  }

  /**
   * 查看监管审核结果
   */
  viewAuditResult(record: any) {
    if (record?.billStatus !== '2') {
      return;
    }
    this.openWainingModal('监管审核结果', record?.result);
  }

  search() {
    this.st.load(1);
  }

  // 导出
  exprot() {
    this.service.exportStart({ ...this.reqParams, pageSize: -1 }, this.service.$api_taxDeclaration_export);
  }

  openWainingModal(content: string, title = '提示') {
    this.modal.warning({
      nzMask: false,
      nzTitle: title,
      nzContent: content
    });
  }
  handleOK() {}
  handleCancel() {
    this.isVisible = false;
  }

  /**
   *
   * @param e
   */
  changeST(e: STChange): void {
    if (e?.type === 'checkbox') {
      if (e?.checkbox!.length === 0) {
        // 全选取消
        this.st.list.forEach((item, index) => {
          this.st.setRow(index, { checked: false });
        });
        this.checkedList = [];
      } else {
        // 取消选择
        if (this.checkedList.length > e?.checkbox!.length) {
          const item = this.checkedList.find(item => !item?.checked);
          this.st.list?.forEach((row, index) => {
            if (row?.driverId === item?.driverId && row?.ltdId === item?.ltdId && row?.taxMonth === item?.taxMonth) {
              this.st.setRow(index, { checked: false });
              this.checkedList = this.checkedList.filter(_item => _item?.id !== row?.id);
            }
          });
        } else {
          // 全选
          const allChecked = this.st?.list.every(item => item.checked);
          if (allChecked) {
            this.st.list?.forEach((row, index) => {
              const flag = this.checkedList.find(_item => _item.id === row?.id);
              if (!flag) {
                this.checkedList.push(row);
              }
            });
            return;
          }
          // 单个新增选择
          const list = e?.checkbox?.filter(item => !this.checkedList.some(_item => _item?.id === item.id));
          list?.forEach(item => {
            this.st.list?.forEach((row, index) => {
              if (row?.driverId === item?.driverId && row?.ltdId === item?.ltdId && row?.taxMonth === item?.taxMonth) {
                this.st.setRow(index, { checked: true });
                const flag = this.checkedList.find(_item => _item.id === row?.id);
                if (!flag) {
                  this.checkedList.push(row);
                }
              }
            });
          });
        }
      }
    }
  }
}
